from __future__ import with_statement
import httplib, urllib, os

from oriolus.pith.packets.packet import FullName

class HttpPublisher:
    def __init__(self, host, path, credential):
        self.__host = host
        self.__path = path
        self.__credential = credential
    
    def publish(self, packet_name_list):
        #headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        conn = httplib.HTTPConnection(self.__host)
        try:
           for paket_name in packet_name_list:
               self.__publish_paket(paket_name, conn)
        finally:
            conn.close()
    
    def __publish_paket(self, packet_filename, connection):
        print "Publishing '%s'" % packet_filename
        
        packet_name = packet_filename[0:packet_filename.find(".zip.ori")]
        
        full_paket_name = FullName.parse(os.path.basename(packet_name))
        with open(packet_filename, 'rb') as f:
            #f = open(packet_filename)              
            query = urllib.urlencode({'name': full_paket_name.name, 'version': full_paket_name.version})
            url = urllib.pathname2url(self.__path) + "?" + query
            if not os.path.isabs(self.__path):
                url = "/" + url 
                
            print "Requesting URL: %s" % url 
            data = f.read()
            print "Sending content: '%s' bytes" % len(data)
            
            try:
                connection.request("POST", url, data) #, headers "POST"        
                response = connection.getresponse()
                print response.status, response.reason
                
                #length = int(response.getheader('content-length'))
                #data = response.read(length)
                data = response.read()
                
                print data
            except Exception, ex:
                print "Read response error %s" % ex                 
            #f.close()
